package public

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"gorm.io/gorm"
	"sync"
	"tino_manager/dao"
)

func SendReservationTemplateMessage(to, time, contract, audit, typeName string) {
	wxMessage := WxMessageReservation{
		ToUer:      to,
		TemplateId: "lGlXBm4gaMF22l9i0qZjnCD-i8fyfCgT-sJXnFDzjHw",
		AppId:      lib.GetStringConf("base.message.appId"),
		Secret:     lib.GetStringConf("base.message.appSecret"),
		//Url:        fmt.Sprintf("https://toolsapi.teachfree.cn/pages/code/code?id=%d", reservation.Id),
		//MiniProgram: map[string]interface{}{
		//	"appid":    lib.GetStringConf("base.weapp.appId"),
		//	"pagepath": "index?index=3",
		//},
		Data: map[string]map[string]interface{}{
			"time3": {
				"value": time,
			},
			"thing8": {
				"value": contract,
			},
			"phrase1": {
				"value": typeName,
			},
			"phrase4": {
				"value": audit,
			},
			"remark": {
				"value": "请您保持电话畅通，我们将联系您",
			},
		},
	}
	wxMessage.Send()
}

func SentToManagerTemplateMessage(tx *gorm.DB, reservationId, time, contract, audit, typeName string) error {
	var manager []dao.Manager
	if result := tx.Model(&dao.Manager{}).Where("is_delete = 0 AND status = 0 AND open_message_status = 1").Find(&manager); result.Error != nil {
		return errors.New("查询失败")
	}
	var wg sync.WaitGroup
	fmt.Println(len(manager), "-------------------------------------")
	for _, item := range manager {
		wg.Add(1)
		go func(wgChild *sync.WaitGroup) {
			wxMessage := WxMessageReservation{
				ToUer:      item.MessageOpenId,
				TemplateId: "lGlXBm4gaMF22l9i0qZjnCD-i8fyfCgT-sJXnFDzjHw",
				AppId:      lib.GetStringConf("base.message.appId"),
				Secret:     lib.GetStringConf("base.message.appSecret"),
				//Url:        fmt.Sprintf("https://toolsapi.teachfree.cn/pages/code/code?id=%d", reservation.Id),
				//MiniProgram: map[string]interface{}{
				//	"appid":    lib.GetStringConf("base.weapp.appId"),
				//	"pagepath": "index?index=3",
				//},
				Data: map[string]map[string]interface{}{
					"time3": {
						"value": time,
					},
					"thing8": {
						"value": contract,
					},
					"phrase1": {
						"value": "有待审批",
					},
					"phrase4": {
						"value": "请审批",
					},
					"remark": {
						"value": "请您保持电话畅通，我们将联系您",
					},
				},
			}
			wxMessage.Send()
			wgChild.Done()
		}(&wg)
	}
	wg.Wait()
	return nil
}
